package com.zuowei.ycy.user.adapter;

import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.and.yzy.frame.adapter.AdapterCallback;
import com.and.yzy.frame.view.button.SelectNumberButtonBase;
import com.facebook.drawee.view.SimpleDraweeView;
import com.zuowei.ycy.R;
import com.zuowei.ycy.user.domain.BusinessSortInfo;
import com.zuowei.ycy.user.view.CircleSelectNumberBtn;
import com.zuowei.ycy.user.view.pinnedheaderlistview.PinnedHeaderListView;

import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class BusinessSortAdapter extends BaseAdapter implements OnScrollListener,
        PinnedHeaderListView.PinnedHeaderAdapter {
    private HashMap<Integer, Integer> hash;
    private static final String TAG = BusinessSortAdapter.class.getSimpleName();
    private ListView leftListView;

    private AdapterCallback mAdapterCallback;

    public void setAdapterCallback(AdapterCallback mAdapterCallback) {

        this.mAdapterCallback = mAdapterCallback;
    }

    public void setLeftListView(ListView leftListView) {
        this.leftListView = leftListView;
    }

    private Context mContext;
    private List<BusinessSortInfo> mData;
    private LayoutInflater mLayoutInflater;





    public BusinessSortAdapter(Context pContext, List<BusinessSortInfo> pData, AdapterCallback mAdapterCallback) {
        mContext = pContext;
        mData = pData;
        mLayoutInflater = LayoutInflater.from(mContext);
        this.mAdapterCallback=mAdapterCallback;

    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 常见的优化ViewHolder


        ViewHolder contentHolder = null;
        if (null == convertView) {
            convertView = mLayoutInflater.inflate(R.layout.buiness_good_sort_choose_item,
                    null);
            contentHolder = new ViewHolder(convertView);

            convertView.setTag(contentHolder);
        } else {
            contentHolder = (ViewHolder) convertView.getTag();
        }

        //隐藏最后一个分割线
        if (mData.get(position).isLast()) {

            contentHolder.mVDivier.setVisibility(View.INVISIBLE);
        } else {

            contentHolder.mVDivier.setVisibility(View.VISIBLE);
        }
        // 获取数据
        final BusinessSortInfo itemEntity = (BusinessSortInfo) getItem(position);

        if (itemEntity.getNumber()==0){
            contentHolder.mBtn_number.setBtn_downVisibility(false);
        }else {
            contentHolder.mBtn_number.setBtn_downVisibility(true);
        }

        contentHolder.mBtn_number.setNum(itemEntity.getNumber()+"");
        contentHolder.mBtn_number.setNumberButtonListener(new SelectNumberButtonBase.NumberButtonListener() {
            @Override
            public void btnNumber(String num,boolean isAdd) {
             //   notifyDataSetChanged();
                itemEntity.setNumber(Integer.parseInt(num));
               mAdapterCallback.adapterInfotoActiity(isAdd,1);

            }
        });

        contentHolder.mGood.setImageURI(Uri.parse(itemEntity.getGoods_picture()));
        contentHolder.mName.setText(itemEntity.getGoods_name());
        contentHolder.mSale.setText("销量" + itemEntity.getSales());
        contentHolder.mPrice.setText("￥"+itemEntity.getGoods_price());



        if (needTitle(position)) {
           contentHolder.mTitle.setText(itemEntity.getG_t_name());
            contentHolder.mTitle.setVisibility(View.VISIBLE);
        } else {
            // 内容项隐藏标题
            contentHolder.mTitle.setVisibility(View.GONE);
        }


        return convertView;
    }

    @Override
    public int getCount() {
        if (null != mData) {
            return mData.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (null != mData && position < getCount()) {
            return mData.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        if (view instanceof PinnedHeaderListView) {

            ((PinnedHeaderListView) view).controlPinnedHeader(firstVisibleItem);
        }

    }


    public static boolean isScroll = false;

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        switch (scrollState) {
            case SCROLL_STATE_FLING:

                break;
            case SCROLL_STATE_IDLE:

                break;
            case SCROLL_STATE_TOUCH_SCROLL:

                isScroll = true;
                break;

        }

    }

    @Override
    public int getPinnedHeaderState(int position) {
        if (getCount() == 0 || position < 0) {
            return PinnedHeaderListView.PinnedHeaderAdapter.PINNED_HEADER_GONE;
        }

        if (isMove(position) == true) {
            return PinnedHeaderListView.PinnedHeaderAdapter.PINNED_HEADER_PUSHED_UP;
        }

        return PinnedHeaderListView.PinnedHeaderAdapter.PINNED_HEADER_VISIBLE;
    }

    @Override
    public void configurePinnedHeader(View headerView, int position, int alpaha) {
        // 设置标题的内容
        Log.i("result", "position==" + position);
        BusinessSortInfo itemEntity = (BusinessSortInfo) getItem(position);
        String headerValue = itemEntity.getG_t_name();
        int type = itemEntity.getType();

        Log.e(TAG, "header = " + headerValue);

        if (!TextUtils.isEmpty(headerValue)) {
            TextView headerTextView = (TextView) headerView
                    .findViewById(R.id.header);
            headerTextView.setText(headerValue);
            if (hash != null) {
                if (hash.containsValue(type) && isScroll) {
                    changeLeftBackGroud(type);
                }
            }

        }

    }


    public void changeLeftBackGroud(int position) {

        if (leftListView == null) {
            return;
        }
        int count = leftListView.getChildCount();


        for (int i = 0; i < count; i++) {
            //向下滚动


            if (i == position - 1) {
                leftListView.getChildAt(i).setBackgroundColor(Color.parseColor("#ffffff"));
            } else {
                leftListView.getChildAt(i).setBackgroundColor(Color.parseColor("#F3F7F5"));
            }
        }

    }

    /**
     * 判断是否需要显示标题
     *
     * @param position
     * @return
     */
    private boolean needTitle(int position) {
        // 第一个肯定是分类
        if (position == 0) {
            return true;
        }

        // 异常处理
        if (position < 0) {
            return false;
        }

        // 当前 // 上一个
        BusinessSortInfo currentEntity = (BusinessSortInfo) getItem(position);
        BusinessSortInfo previousEntity = (BusinessSortInfo) getItem(position - 1);
        if (null == currentEntity || null == previousEntity) {
            return false;
        }

        int currentTitle = currentEntity.getType();
        int previousTitle = previousEntity.getType();
        if (0 == previousTitle || 0 == currentTitle) {
            return false;
        }

        // 当前item分类名和上一个item分类名不同，则表示两item属于不同分类
        if (currentTitle == previousTitle) {
            return false;
        }

        return true;
    }

    private boolean isMove(int position) {
        //     Log.i("result", "position==" + position);
        // 获取当前与下一项
        BusinessSortInfo currentEntity = (BusinessSortInfo) getItem(position);
        BusinessSortInfo nextEntity = (BusinessSortInfo) getItem(position + 1);
        if (null == currentEntity || null == nextEntity) {
            return false;
        }

        // 获取两项header内容
        int currentTitle = currentEntity.getType();
        int nextTitle = nextEntity.getType();
        if (0 == currentTitle || 0 == nextTitle) {
            return false;
        }
        // 当前不等于下一项header，当前项需要移动了
        if (currentTitle != nextTitle) {
            return true;
        }

        return false;
    }

    public void setLeftListView(ListView lv_Left, HashMap<Integer, Integer> hash) {
        this.leftListView = lv_Left;
        this.hash = hash;
    }


    /**
     * 添加所有
     */
    public void addAll(List<BusinessSortInfo> list_) {

        mData.addAll(list_);
        notifyDataSetChanged();

    }


    /**
     * 查找所有
     */
    public List<BusinessSortInfo> findAll() {
        if (mData != null) {
            return mData;
        } else {
            return null;
        }
    }

    /**
     * 删除所有
     */
    public void removeAll() {

        mData.clear();
        notifyDataSetChanged();
    }

    /**
     * This class contains all butterknife-injected Views & Layouts from layout file 'index_take_out_mian_item.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast)
     */
    static class ViewHolder {
        @Bind(R.id.title)
        TextView mTitle;
        @Bind(R.id.tv_name)
        TextView mName;
        @Bind(R.id.tv_sale_num)
        TextView mSale;
        @Bind(R.id.tv_price)
        TextView mPrice;
        @Bind(R.id.iv_good)
        SimpleDraweeView mGood;

       @Bind(R.id.btn_number)
       CircleSelectNumberBtn mBtn_number;

        @Bind(R.id.v_divier)
        View mVDivier;


        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
